package org.amphiprion.kidcalendar.entity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.amphiprion.kidcalendar.entity.Period.PeriodType;

public class VacationRule implements Rule {
	private String type;
	private VacationCalendar vacationCalendar;

	private List<Rule> rules = new ArrayList<Rule>();

	@Override
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public VacationCalendar getVacationCalendar() {
		return vacationCalendar;
	}

	public void setVacationCalendar(VacationCalendar vacationCalendar) {
		this.vacationCalendar = vacationCalendar;
	}

	@Override
	public List<Rule> getSubRules() {
		return rules;
	}

	@Override
	public Period verifyDate(Date date) {
		Calendar cDate = new GregorianCalendar();
		cDate.setTime(date);

		for (Vacation vac : vacationCalendar.getVacations()) {
			try {
				Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(vac.getFrom());
				Calendar cstart = new GregorianCalendar();
				cstart.setTime(startDate);
				cstart.set(Calendar.HOUR_OF_DAY, 0);
				cstart.set(Calendar.MINUTE, 0);
				cstart.set(Calendar.SECOND, 0);
				cstart.set(Calendar.MILLISECOND, 0);

				Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(vac.getTo());
				Calendar cEnd = new GregorianCalendar();
				cEnd.setTime(endDate);
				cEnd.set(Calendar.HOUR_OF_DAY, 23);
				cEnd.set(Calendar.MINUTE, 59);
				cEnd.set(Calendar.SECOND, 59);
				cEnd.set(Calendar.MILLISECOND, 0);

				int nbMilli = (int) ((cEnd.getTimeInMillis() - cstart.getTimeInMillis()) / 2);
				if ("FIRST_HALF_VACATION".equals(type)) {
					cEnd.add(Calendar.MILLISECOND, -nbMilli);
					cEnd.set(Calendar.HOUR_OF_DAY, 23);
					cEnd.set(Calendar.MINUTE, 59);
					cEnd.set(Calendar.SECOND, 59);
					cEnd.set(Calendar.MILLISECOND, 0);

				} else if ("SECOND_HALF_VACATION".equals(type)) {
					cstart.add(Calendar.MILLISECOND, nbMilli);
					cstart.set(Calendar.HOUR_OF_DAY, 0);
					cstart.set(Calendar.MINUTE, 0);
					cstart.set(Calendar.SECOND, 0);
					cstart.set(Calendar.MILLISECOND, 0);

				}

				if (cDate.after(cstart) && cDate.before(cEnd)) {
					return new Period(cstart.getTime(), cEnd.getTime(), this, PeriodType.VACATION);
				}

			} catch (ParseException e) {
				e.printStackTrace();
				continue;
			}

		}
		return null;
	}

}
